// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// g [author] rhyme_lph
// v [email]  rhymelph@gmail.com
// h [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/fixed_asset_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/http_service/http_asset_service.dart';
import 'package:finance_app/src/mixin/from_attach_mixin.dart';
import 'package:finance_app/src/page/all_reports/date_report_page.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/calendar_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/currency_bottom_sheet.dart';
import 'package:flutter/material.dart';

class SalesOfFixedAssetProvider extends BaseProvider with FormAttachMixin {
  SettingDataCurrency currency;
  List<OcrAttachmentEntity> attachedFiles;
  TextEditingController salePriceController = TextEditingController();
  FocusNode salePriceFocusNode = FocusNode();

  TextEditingController notesController = TextEditingController();
  FocusNode notesFocusNode = FocusNode();

  DateTime salesDate = DateTime.tryParse(Config.currentFY.endDate);
  FixedAssetEntity selectedAsset;
  int id;
  String assetName;
  int salesId;
  bool isEdit = true;

  List<String> menuList = [
    'View Payment',
  ];

  void onSelectMenu(String value) {
    switch (value) {
      case 'View Payment':
        onViewPayment();
        break;
    }
  }

  void onViewPayment() {
    Routes.navigateTo(RouterGenProviders.newCashInPage, params: {
      'data': TransactionEntity()..transactionableId = salesId,
    });
  }

  @override
  Future get dataFuture => null;

  @override
  void dispose() {
    super.dispose();
    salePriceController.dispose();
    salePriceFocusNode.dispose();
    notesController.dispose();
    notesFocusNode.dispose();
  }

  void onSave() async {
    salePriceFocusNode.unfocus();
    num price = num.parse(salePriceController.text, (e) => null);
    if (price == null) {
      showToast(S.current.please_enter_sales_price);
      return;
    }

    List<int> attachmentIds = await uploadFiles();
    if (attachmentIds == null) return;

    FixedAssetEntity soldAsset;
    await post(
        HttpAssetService.sellAsset(
          id,
          sell_at: DateTimeUtils.formatDateTime(
            salesDate,
            'yyyy-MM-dd',
          ),
          sell_currency_code: currency?.key,
          sell_price: price,
          notes: notesController.text,
          attachment_ids: attachmentIds,
        ),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) {
      soldAsset = getEntityFromResult<FixedAssetEntity>(result);
    });

    obtainContext?.call((context) {
      Navigator.of(context).pop(soldAsset);
      Providers.get<DateReportProvider>(RouterGenProviders.dateReportPage, null)
          ?.onRequestRefresh();
    });
  }

  void unFocus() {
    salePriceFocusNode.unfocus();
    notesFocusNode.unfocus();
  }

  void onChangeCurrency() {
    unFocus();
    obtainContext?.call((context) async {
      currency = await showCurrencyBottomSheet(context, currency);
      update();
    });
  }

  void onChangeSalesDate() {
    unFocus();
    obtainContext?.call((context) async {
      salesDate = await showCalendarBottomSheet(context, salesDate);
      update();
    });
  }

  void onSelectAsset() async {
    unFocus();
    selectedAsset = await Routes.navigateTo(RouterGenProviders.fixedAssetPage,
        params: {'select': selectedAsset});
    id = selectedAsset?.id;
    assetName = selectedAsset?.name;
    update();
  }

  @override
  List<OcrAttachmentEntity> get attachments => attachedFiles;
}
